<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-row :gutter="20">
        <el-col :span="6">
          <el-input v-model="queryInfo.query" @clear="getUserList" clearable>
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUserList"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="6">
          <el-button type="primary" @click="dialogVisible = true"
            >添加用户</el-button
          >
        </el-col>
        <!-- 添加用户的对话框 -->
        <el-dialog
          title="添加用户"
          :visible.sync="dialogVisible"
          width="50%"
          @close="closeAddUser"
        >
          <el-form
            :model="addUser"
            :rules="addUserRules"
            ref="addUserRuleForm"
            label-width="100px"
            class="demo-ruleForm"
          >
            <el-form-item label="用户名" prop="username">
              <el-input v-model="addUser.username"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password">
              <el-input v-model="addUser.password"></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="addUser.email"></el-input>
            </el-form-item>
            <el-form-item label="手机号" prop="mobile">
              <el-input v-model="addUser.mobile"></el-input>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="addUserInfo">确 定</el-button>
          </span>
        </el-dialog>
        <!-- 编辑用户的对话框 -->
        <el-dialog title="编辑用户" :visible.sync="showUserDialog" width="50%">
          <el-form
            :model="editUser"
            :rules="editUserRule"
            ref="editUserForm"
            label-width="100px"
            class="demo-ruleForm"
          >
            <el-form-item label="用户名" prop="username">
              <el-input v-model="editUser.username" disabled></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="editUser.email"></el-input>
            </el-form-item>
            <el-form-item label="手机号" prop="mobile">
              <el-input v-model="editUser.mobile"></el-input>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="showUserDialog = false">取 消</el-button>
            <el-button type="primary" @click="editChecked">确 定</el-button>
          </span>
        </el-dialog>
      </el-row>
      <el-table :data="userList" style="width: 100%" border stripe>
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="username" label="姓名" width="180">
        </el-table-column>
        <el-table-column prop="email" label="邮箱" width="180">
        </el-table-column>
        <el-table-column prop="mobile" label="电话" width="180">
        </el-table-column>
        <el-table-column prop="role_name" label="角色" width="180">
        </el-table-column>
        <el-table-column label="状态" width="180">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              @change="userStateChange(scope.row)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180">
          <template slot-scope="scope">
            <!-- 编辑按钮 -->
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-edit"
              @click="editUserClick(scope.row.id)"
            >
            </el-button>
            <!-- 删除按钮 -->
            <el-button
              type="danger"
              size="mini"
              icon="el-icon-delete"
              @click="deleteUserInfo(scope.row.id)"
            ></el-button>
            <!-- 分配权限按钮 -->
            <el-tooltip
              content="分配权限"
              :enterable="false"
              placement="top-start"
            >
              <el-button
                type="info"
                size="mini"
                icon="el-icon-message"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[2, 4, 6, 8]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="this.total"
      >
      </el-pagination>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    var checkEmail = (rule, value, cb) => {
      const regEmail = /^\w+@\w+(\.\w+)+$/
      if (regEmail.test(value)) {
        return cb()
      }
      cb(new Error('请输入正确的邮箱'))
    }
    var checkMobile = (rule, value, cb) => {
      const regMobile = /^1[34578]\d{9}$/
      if (regMobile.test(value)) {
        return cb()
      }
      cb(new Error('请输入正确的手机号'))
    }
    return {
      // 编辑用户对话框
      editUser: {
        email: '',
        mobile: ''
      },
      editUserRule: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          {
            min: 3,
            max: 10,
            message: '长度在 3 到 10 个字符',
            trigger: 'blur'
          },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      showUserDialog: false,
      queryInfo: {
        query: '',
        // 当前的页数
        pagenum: 1,
        // 当前每页显示多少条数据
        pagesize: 2
      },
      userList: [],
      total: 0,
      // 添加用户弹窗
      dialogVisible: false,
      // 添加用户的表单验证
      addUser: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      addUserRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          {
            min: 3,
            max: 10,
            message: '长度在 3 到 10 个字符',
            trigger: 'blur'
          },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    // 根据id删除用户
    async deleteUserInfo(id) {
      const tipInfo = await this.$confirm(
        '此操作将永久删除该文件, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      if (tipInfo !== 'confirm') {
        this.$message.info('取消删除')
      } else {
        this.$message.success('删除成功')
        const { data: res } = await this.$http.delete('users/' + id)
        console.log(res)
        if (res.meta.status !== 200) return
        this.getUserList()
      }
      // 删除时返回值是promise 可以用 async await处理
      // 确定删除 返回字符换 confirm
      // 取消删除 返回字符串 cancel
      // console.log(tipInfo)
    },
    // 修改用户前的预验证
    editChecked() {
      this.$refs.editUserForm.validate(async valid => {
        if (!valid) {
          this.$message.error('修改用户失败，请输入正确信息')
        } else {
          const { data: res } = await this.$http.put(
            'users/' + this.editUser.id,
            {
              email: this.editUser.email,
              mobile: this.editUser.mobile
            }
          )
          if (res.meta.status !== 200) {
            this.$message.error('更新失败')
          } else {
            this.getUserList()
            this.showUserDialog = false
            this.$message.success('更新成功')
          }
        }
      })
    },
    // 点击弹出编辑用户的对话框
    async editUserClick(id) {
      this.showUserDialog = true
      const { data: res } = await this.$http.get('users/' + id)
      console.log(res)
      this.editUser = res.data
    },
    // 点击确定是对表单的预校验
    addUserInfo() {
      this.$refs.addUserRuleForm.validate(async valid => {
        // console.log(valid)
        if (!valid) {
          return this.$message.error('请输入正确信息')
        } else {
          // 发起添加用户的请求
          const { data: res } = await this.$http.post('users', this.addUser)
          console.log(res)
          if (res.meta.status !== 201) {
            this.$message.error('添加用户失败')
          } else {
            this.$message.success('添加用户成功')
            this.dialogVisible = false
            this.getUserList()
          }
        }
      })
    },
    // 关闭时重置对话框的验证
    closeAddUser() {
      this.$refs.addUserRuleForm.resetFields()
    },
    // 搜索用户
    // async searchUserInfo() {
    //   const { data: res } = await this.$http.get(`users/${this.userList.id}`)
    //   console.log(res)
    // },
    // switch状态改变的方法
    async userStateChange(userInfo) {
      // console.log(userInfo)
      const { data: res } = await this.$http.put(
        `users/${userInfo.id}/state/${userInfo.mg_state}`
      )
      if (res.meta.status !== 200) {
        this.$message.error('更新状态失败')
        userInfo.mg_state = !userInfo.mg_state
      } else {
        this.$message.success(res.meta.msg)
      }
      // console.log(res)
    },
    // 分页的方法
    handleSizeChange(newSize) {
      // console.log(newSize)
      this.queryInfo.pagesize = newSize
      this.getUserList()
    },
    handleCurrentChange(newPage) {
      // console.log(newPage)
      this.queryInfo.pagenum = newPage
      this.getUserList()
    },
    // 获取用户数据
    async getUserList() {
      const { data: res } = await this.$http.get('users', {
        params: this.queryInfo
      })
      if (res.meta.status !== 200) {
        return this.$message.error('获取用户列表失败')
      }
      // console.log(res.data)
      this.userList = res.data.users
      this.total = res.data.total
    }
  }
}
</script>

<style scoped>
.el-table {
  margin-top: 20px;
}
.el-breadcrumb {
  margin-bottom: 10px;
}
</style>
